import Geom from '../geom'
import {Bounds} from '../utils'

function exportPointData(points) {
  let data = null
  if (!points || points.length === 0) {
    data = {partCount: 0, pointCount: 0}
  } else {
    const path = {
      points: points,
      pointCount: points.length,
      bounds: Geom.getPathBounds(points)
    }
    data = {
      bounds: path.bounds,
      pathData: [path],
      partCount: 1,
      pointCount: path.pointCount
    }
  }
  return data
}
// TODO: remove duplication with internal.getPathMetadata()
function exportPathData(shape, arcs, type) {
  // kludge until Shapefile exporting is refactored
  if (type == 'point') return exportPointData(shape)

  let pointCount = 0
  const bounds = new Bounds()
  const paths = []

  if (shape && (type == 'polyline' || type == 'polygon')) {
    shape.forEach((arcIds, i) => {
      const iter = arcs.getShapeIter(arcIds)
      const path = exportPathCoords(iter)
      let valid = true
      if (type == 'polygon') {
        path.area = Geom.getPlanarPathArea2(path.points)
        valid = path.pointCount > 3 && path.area !== 0
      } else if (type == 'polyline') {
        valid = path.pointCount > 1
      }
      if (valid) {
        pointCount += path.pointCount
        path.bounds = Geom.getPathBounds(path.points)
        bounds.mergeBounds(path.bounds)
        paths.push(path)
      } else {
        // verbose("Skipping a collapsed", type, "path")
      }
    })
  }

  return {
    pointCount: pointCount,
    pathData: paths,
    pathCount: paths.length,
    bounds: bounds
  }
}
function exportPathCoords(iter) {
  const points = []
  let i = 0
  let x = null
  let y = null
  let prevX = null
  let prevY = null
  while (iter.hasNext()) {
    x = iter.x
    y = iter.y
    if (i === 0 || prevX != x || prevY != y) {
      points.push([x, y])
      i++
    }
    prevX = x
    prevY = y
  }
  return {
    points: points,
    pointCount: points.length
  }
}
export default {
  exportPathData,
}